package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gyf.immersionbar.ImmersionBar;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshControllerEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.adapter.AddLoadDeviceAdapter;
import com.qiantu.phone.ui.dialog.BottomAddDeviceEditDialog;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import okhttp3.Call;

import static com.qiantu.api.entity.RoomBean.ROOM_COMMON_SERIALNO;

/**
 * time   : 2021/12/22
 */
public final class AddDeviceSuccessActivity extends AppActivity {

    private ImageView iconDevice;
    private TextView tvAddDeviceHint;
    private View loadDeviceLayout;
    private RecyclerView loadDeviceRecyclerView;
    private TextView btnComplete;
    private AddLoadDeviceAdapter mAddLoadDeviceAdapter;
    private BottomAddDeviceEditDialog mBottomAddDeviceEditDialog;
    private DeviceBean editDevice;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_device_success;
    }

    @Override
    protected void initView() {
        ImmersionBar.setTitleBar(this, findViewById(R.id.title_view));
        iconDevice = findViewById(R.id.icon_device);
        tvAddDeviceHint = findViewById(R.id.tv_add_device_hint);
        String controllerName = getIntent().getStringExtra("controllerName");
        String controllerImageUrl = getIntent().getStringExtra("controllerImageUrl");
        GlideApp.with(iconDevice).load(controllerImageUrl).into(iconDevice);
        if (controllerName.equals("1")){
            tvAddDeviceHint.setText(getString(R.string.add_device_success_holder_repetition));
        }else {
            tvAddDeviceHint.setText(getString(R.string.add_device_success_holder, controllerName));
        }

        loadDeviceLayout = findViewById(R.id.load_device_layout);
        loadDeviceRecyclerView = findViewById(R.id.load_device_recycler_view);
        btnComplete = findViewById(R.id.btn_complete);
        setOnClickListener(btnComplete);
    }

    @Override
    protected void initData() {
        String controllerSerialNo = getIntent().getStringExtra("controllerSerialNo");
        if (controllerSerialNo.equals("1")){
            loadDeviceLayout.setVisibility(View.INVISIBLE);
        }else {
            List<DeviceBean> data = LLDeviceDBManager.getInstance(getContext()).getDeviceByControllerSerialNo(controllerSerialNo);
            if(data == null || data.size() == 0){
                loadDeviceLayout.setVisibility(View.INVISIBLE);
            }else{
                loadDeviceLayout.setVisibility(View.VISIBLE);
                loadDeviceRecyclerView.setLayoutManager(new LinearLayoutManager(this));
                mAddLoadDeviceAdapter = new AddLoadDeviceAdapter(this);
                loadDeviceRecyclerView.setAdapter(mAddLoadDeviceAdapter);
                mAddLoadDeviceAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                        editDevice = mAddLoadDeviceAdapter.getData().get(position);
                        showBottomAddDeviceEditDialog();
                    }
                });
                mAddLoadDeviceAdapter.setData(data);
            }
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_complete:
                //控制器下有设备
                if(mAddLoadDeviceAdapter != null && mAddLoadDeviceAdapter.getData() != null && mAddLoadDeviceAdapter.getData().size() > 0){
                    EventBus.getDefault().post(new RefreshControllerEvent());
                    EventBus.getDefault().post(new RefreshDeviceListEvent());
                }else{
                    EventBus.getDefault().post(new RefreshControllerEvent());
                }
                ActivityManager.getInstance().finishActivity(AddDevice1Activity.class);
                ActivityManager.getInstance().finishActivity(AddDevice2Activity.class);
                ActivityManager.getInstance().finishActivity(AddDevice3Activity.class);
                ActivityManager.getInstance().finishActivity(SetNetWorkWifiActivity.class);
                finish();
                break;
        }
    }

    private void showBottomAddDeviceEditDialog() {
        if (mBottomAddDeviceEditDialog == null) {
            mBottomAddDeviceEditDialog = new BottomAddDeviceEditDialog(this);
            mBottomAddDeviceEditDialog.setDialogClickListener(new BottomAddDeviceEditDialog.DialogClickListener() {
                @Override
                public void onDeviceIconClick() {
                    Intent intent = new Intent(getContext(), DeviceIconSelectActivity.class);
                    intent.putExtra("type", editDevice.getType());
                    intent.putExtra("deviceType", editDevice.getDeviceType());
                    intent.putExtra("selectIcon", editDevice.getImageUrl());
                    startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                        @Override
                        public void onActivityResult(int resultCode, Intent data) {
                            if (resultCode == RESULT_OK) {
                                String selectIconUrl = data.getStringExtra("DATA");
                                editDevice.setImageUrl(selectIconUrl);
                                mBottomAddDeviceEditDialog.setDeviceIcon(editDevice.getImageUrl());
                            }
                        }
                    });
                }

                @Override
                public void onDeviceFloorRoomClick() {
                    Intent intent = new Intent(getContext(), SelectFloorRoomActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                        @Override
                        public void onActivityResult(int resultCode, Intent data) {
                            if (resultCode == RESULT_OK){
                                String serialNo = data.getStringExtra("serialNo");
                                String roomName = data.getStringExtra("roomName");
                                String floorSerialNo = data.getStringExtra("floorSerialNo");
                                if(serialNo.equals(floorSerialNo)){
                                    editDevice.setRoomSerialNo("");
                                    editDevice.setLinkType(3);
                                    editDevice.setRoomName("");
                                }else{
                                    editDevice.setRoomSerialNo(serialNo);
                                    if (ROOM_COMMON_SERIALNO.equals(serialNo)){
                                        editDevice.setLinkType(2);
                                    }else {
                                        editDevice.setLinkType(1);
                                    }
                                    editDevice.setRoomName(roomName);
                                }
                                if(!TextUtils.isEmpty(floorSerialNo)){
                                    FloorBean floor = LLFloorDBManager.getInstance(getContext()).getFloorByFloorSerialNo(floorSerialNo);
                                    if(floor != null){
                                        editDevice.setFloorName(floor.getFloorName());
                                        editDevice.setFloorSerialNo(floor.getFloorSerialNo());
                                    }
                                }
                                mBottomAddDeviceEditDialog.setFloorRoom(TextUtils.isEmpty(editDevice.getFloorName()) ? roomName : editDevice.getFloorName() + roomName);
                            }
                        }
                    });
                }

                @Override
                public void onConfirmClick() {
                    String name = mBottomAddDeviceEditDialog.getText();
                    if(TextUtils.isEmpty(name)){
                        toast(R.string.device_name);
                        return;
                    }
                    editDevice.setName(name);
                    updateDevice();
                    mBottomAddDeviceEditDialog.dismiss();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomAddDeviceEditDialog);
        }
        mBottomAddDeviceEditDialog.setDeviceName(editDevice.getName());
        mBottomAddDeviceEditDialog.setDeviceIcon(editDevice.getOnImageUrl());
        mBottomAddDeviceEditDialog.setFloorRoom(LLRoomDBManager.getInstance(getContext()).getFloorRoomName(editDevice.getRoomSerialNo()));
        mBottomAddDeviceEditDialog.show();
    }

    private void updateDevice(){
        LLHttpManager.modifyDevice(this, editDevice, new HttpCallback<HttpData<Void>>(this) {
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.setting));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                LLDeviceDBManager.getInstance(getContext()).put(editDevice);
                toast(R.string.set_success);
                mAddLoadDeviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {

    }

    /**
     * 状态栏字体深色模式
     */
    protected boolean isStatusBarDarkFont() {
        return AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont);
    }
}